const { promisify } = require("util");
const fs = require("fs");
const path = require("path");
const writeFile = promisify(fs.writeFile);

exports.storeImg = (fileDir) => {
  return async (req) => {
    const { originalname, buffer } = req.file;
    let filePath;

    try {
      // 将内存中的Buffer写入磁盘
      if (!fs.existsSync(fileDir)) {
        fs.mkdirSync(fileDir, { recursive: true });
      }
      const fileExt = path.extname(originalname);
      const fileName = `${Date.now()}-${Math.round(
        Math.random() * 1e9
      )}${fileExt}`;
      filePath = path.join(fileDir, fileName);
      await writeFile(filePath, buffer);
      return Promise.resolve({ fileName, filePath });
    } catch (error) {
      console.log("upload  ", error);
      fs.rmSync(filePath);
      return Promise.reject(error);
    }
  };
};
